package com.lzx.common;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * LocaleReslover
 *
 * @author liuzp
 * @version 1.0
 * @createTime 2019-06-10 11:31
 * @description 国际化配置
 **/

public class MyLocaleReslover implements LocaleResolver {

    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        Cookie[] cookies = httpServletRequest.getCookies(); //获取cookie数组
        String loacle = "";
        for (Cookie cookie : cookies) {//遍历cookie数组
//            System.out.println(cookie.getName());//获取cookie的名字
//            System.out.println(cookie.getValue()); //获取cookie的值
            if (cookie.getName().equals("locale")) {
                loacle = cookie.getValue();
            }
        }
//        System.out.println("===========locale:" + loacle);
        String localeStr = httpServletRequest.getParameter("locale");
//        Locale locale = Locale.getDefault();//获取默认语言环境
        Locale locale = httpServletRequest.getLocale();//获取请求客户端的语言环境
        if (localeStr != null && !StringUtils.isEmpty(localeStr)) {
            String[] split = localeStr.split("_");
            locale = new Locale(split[0], split[1]);
        } else {
            if (!StringUtils.isEmpty(loacle)) {
                String[] split = loacle.split("_");
                locale = new Locale(split[0], split[1]);
            }
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
    }

}
